package com.hanter.demo.raddemo;

import android.content.ContentResolver;
import android.net.Uri;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.io.IOException;
import java.io.InputStream;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;
import okio.Okio;

public class UriRequestBody extends RequestBody {

    private final MediaType contentType;
    private final ContentResolver contentResolver;
    private final Uri uri;

    public UriRequestBody(@Nullable MediaType contentType, @NonNull ContentResolver contentResolver, Uri uri) {
        if (uri == null) throw new NullPointerException("uri == null");
        this.contentType = contentType;
        this.contentResolver = contentResolver;
        this.uri = uri;
    }

    @Nullable
    @Override
    public MediaType contentType() {
        return contentType;
    }

    @Override
    public long contentLength() throws IOException {
        return -1;
    }

    @Override
    public void writeTo(@NonNull BufferedSink sink) throws IOException {
        try (InputStream is = contentResolver.openInputStream(uri)) {
            if (is == null) {
                throw new IOException("uri openInputStream not found.");
            }
            sink.writeAll(Okio.source(is));
        }
    }
}
